/**
 * 
 */
package com.zxc.curator.atomic;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryForever;
import org.apache.curator.utils.CloseableUtils;

/**
 * @author Administrator
 *
 */
public class AtomicDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString("192.168.18.100:2181")  
		        .sessionTimeoutMs(30000)  
		        .connectionTimeoutMs(30000)  
		        .canBeReadOnly(false)  
		        .retryPolicy(new ExponentialBackoffRetry(1000, Integer.MAX_VALUE))  
		        //.namespace("shijie99.com")  
		        //.defaultData(null)  
		        .build();  
		try {
		  client.start();  
		  // 原子数字操作
	      DistributedAtomicInteger adi = new DistributedAtomicInteger(client, "/test/atomic/integer2", new RetryForever(5000));
	      System.out.println("初始化值："+adi.initialize(1));// 默认为1
	      System.out.println("自增1："+adi.increment().postValue());
	      System.out.println("自减1："+adi.decrement().postValue());
	      System.out.println("比较且修改值："+adi.compareAndSet(1, 2).postValue());// 如果当前值等于2，则更新为3
	      adi.forceSet(1);
	      System.out.println("强制修改值："+adi.get().postValue());
	      System.out.println("加2："+adi.add(2).postValue());
	      System.out.println("尝试加1："+adi.trySet(-1).postValue());
	      System.out.println("尝试加1："+adi.trySet(1).preValue());
		} catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            CloseableUtils.closeQuietly(client);  
        }
		 
	}

}
